package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.ForumAPIService;
import server.controller.WebAdapter;
import database.DBHandler;
import database.DatabaseStub;
import forum.Member;

/**
 * Servlet implementation class viewFriends
 */
public class viewFriends extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public viewFriends() {
		super();
	}

	@Override
	public void init() {
		try {
			super.init();
		} catch (ServletException e) {
			System.err.println("Error in initializing register servlet!!!");
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		ForumAPIService db = WebAdapter.getInstance();
		session.setAttribute("forumID", null);
		session.setAttribute("threadID", null);
		String username = (String) session.getAttribute("username");
		if (username != null) {
			if ((session.getAttribute("isLoggedIn") != null)
					&& (Boolean) session.getAttribute("isLoggedIn")) {
				String action = request.getParameter("do");
				if (action != null && action.equals("ajaxShowFriend")) {
					response.setContentType("text/xml");
					response.setHeader("Cache-Control", "no-cache");// browser
																	// won't
																	// save the
																	// results
																	// ahead
					String name = "";
					if (request.getParameter("name") != null)
						name = request.getParameter("name");
					Member friend = db.getInfoAboutFriend(name);
					String ans = this.createStrAboutFriend(friend);
					response.getWriter().write(
							"<div align=\"left\" id=\"friend" + name + "\"> "
									+ ans + " </div>");
					response.getWriter().flush();
					return;
				}

				if (action != null && action.equals("check")){
					System.out.println("view forums processor. check");
					int notify = ((WebAdapter) db).getUserNotifies(username);
					response.setContentType("text/xml");
					response.setHeader("Cache-Control", "no-cache");
					String ans = "<response>";
					//check friend notification
					int res = notify & WebAdapter.FRIEND_NOTIFY;
					if (res > 0) {
						ans  += "<friend>y</friend>\n";
					}
					else
						ans  += "<friend>n</friend>\n";
					// check author notification
					res = notify & WebAdapter.AUTHOR_NOTIFY;
					if (res > 0)
						ans += "<author>y</author>\n";
					else
						ans += "<author>n</author>\n";
					ans += "<viewer>n</viewer>\n";
					ans += "</response>";
					System.out.println(ans);
					response.getWriter().write(ans);
					response.getWriter().flush();
					return;
				}
				
				List<Member> friends = db.getFriends(session);
				List<String> friendsNames = new ArrayList<String>();
				for (int i = 0; i < friends.size(); i++) {
					friendsNames.add(friends.get(i).getUsername());
				}
				request.setAttribute("friends", friendsNames);
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/friendsList.jsp");
				dispatcher.forward(request, response);
			} else {
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/Error.jsp");
				request.setAttribute("errorMsg", "The user " + username
						+ " is not logged in!");
				request.setAttribute(
						"errorLink",
						"http://" + request.getServerName() + ":"
								+ request.getServerPort()
								+ request.getContextPath());
				dispatcher.forward(request, response);
			}
		} else {
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");
			request.setAttribute("errorMsg", "There is no user!!!");
			request.setAttribute(
					"errorLink",
					"http://" + request.getServerName() + ":"
							+ request.getServerPort()
							+ request.getContextPath());
			dispatcher.forward(request, response);
		}
	}

	private String createStrAboutFriend(Member friend) {
		String ans = "";
		ans += "<p>\n";
		ans += "\n<br> <b> First Name: " + friend.getFirstName() + "</b>";
		ans += "\n <br> <b> Last Name: " + friend.getLastName() + "</b>";
		ans += "\n <br> <b> Email: " + friend.getEMail() + "</b> ";
		ans += "\n <br> <b> Gender: " + friend.getGender() + "</b>\n<br>";
		ans += "\n</p>";
		return ans;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected synchronized void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	@Override
	public void destroy() {
		super.destroy();
	}

}
